﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using DeepEarth.Core.Controls;

namespace DeepEarth.Toolkit.Common.Controls
{
    public class TemplatedListBox : ListBox
    {
        #region Properties
        public static readonly DependencyProperty SelectedCommandProperty = DependencyProperty.Register("SelectedCommand", typeof(ICommand), typeof(TemplatedListBox), null);
        public ICommand SelectedCommand
        {
            get { return (ICommand)GetValue(SelectedCommandProperty); }
            set { SetValue(SelectedCommandProperty, value); }
        }

        public static readonly DependencyProperty TemplateSelectorProperty = DependencyProperty.Register("TemplateSelector", typeof(TemplateSelector), typeof(TemplatedListBox), null);
        public TemplateSelector TemplateSelector
        {
            get { return (TemplateSelector)GetValue(TemplateSelectorProperty); }
            set { SetValue(TemplateSelectorProperty, value); }
        }

        public static readonly DependencyProperty AlternateBackgroundProperty = DependencyProperty.Register("AlternateBackground", typeof(Brush), typeof(TemplatedListBox), null);
        public Brush AlternateBackground
        {
            get { return (Brush)GetValue(AlternateBackgroundProperty); }
            set { SetValue(AlternateBackgroundProperty, value); }
        }
        #endregion

        protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
        {
            base.PrepareContainerForItemOverride(element, item);

            if (TemplateSelector != null)
            {
                var myTemplate = TemplateSelector.FindTemplate<DataTemplate>(item);

                var itemCon = (ListBoxItem)element;
                if (myTemplate != null)
                    itemCon.ContentTemplate = myTemplate;

                itemCon.Background = IsInAlternatePosition(item) ? (AlternateBackground ?? Background) : Background;
            }
        }

        bool IsInAlternatePosition(object item)
        {
            var index = 0;
            if (ItemsSource != null)
            {
                foreach (var o in ItemsSource)
                {
                    if (ReferenceEquals(o, item))
                        break;

                    index++;
                }
            }

            return index % 2 == 1;
        }

        public TemplatedListBox()
        {
            AddHandler(MouseLeftButtonDownEvent, new MouseButtonEventHandler((o, e) => HandleSelection()), true);
        }

        void HandleSelection()
        {
            var selectedItem = SelectedItem;

            if (SelectedCommand != null)
            {
                SelectedCommand.Execute(selectedItem);
            }
        }
    }
}